# -*- coding: utf-8 -*-
from db.mysql import MysqlClient
import requests
from itertools import product
from common.helper import Helper
from common.config import *
from urllib.parse import urlencode
from pyquery import PyQuery as pq


class Spider(object):
    def __init__(self):
        self.mysql = MysqlClient()
        self.name = "阳光个人意外伤害保险"

    # 生产产品数据
    def genProductInfo(self):
        professions = self.getProfessionInfo()
        plan = {
            "planA": {
                "days": ["1y"],
                "people_count": ["1"],
                "accident_death": ["10000"],
                "accident_disable": ["10000"],
                "accident_medical": ["0", "1000"],
                "accident_hospital": ["0"],
                "professions": ["{0}|{1}|{2}".format( data["level"],data["code"],data["name"]) for data in professions ]
            },
            "planB": {
                "days": ["1y"],
                "people_count": ["1"],
                "accident_death": ["20000"],
                "accident_disable": ["20000"],
                "accident_medical": ["0", "1000", "2000"],
                "accident_hospital": ["0"],
                "professions": ["{0}|{1}|{2}".format( data["level"],data["code"],data["name"]) for data in professions ]
            },
            "planC": {
                "days": ["1y"],
                "people_count": ["1"],
                "accident_death": ["50000"],
                "accident_disable": ["50000"],
                "accident_medical": ["0", "1000", "2000", "5000"],
                "accident_hospital": ["0"],
                "professions": ["{0}|{1}|{2}".format( data["level"],data["code"],data["name"]) for data in professions ]
            },
            "planD": {
                "days": ["1y"],
                "people_count": ["1"],
                "accident_death": ["100000"],
                "accident_disable": ["100000"],
                "accident_medical": ["0", "1000", "2000", "5000", "10000"],
                "accident_hospital": ["0", "20/天"],
                "professions": ["{0}|{1}|{2}".format( data["level"],data["code"],data["name"]) for data in professions ]
            }
        }

        for k in plan:

            for v in product(plan[k]["days"], plan[k]["people_count"], plan[k]["accident_death"],
                             plan[k]["accident_disable"], plan[k]["accident_medical"], plan[k]["accident_hospital"],
                             plan[k]["professions"]):
                data = Helper.formatProductInfo(plan[k], v)

                yield data

    # 执行爬虫
    def requestJson(self):
        for v in self.genProductInfo():

            params = '''
            agentId: 
            sessionKey: myInsurance94986813-16e5-43fe-9991-f6acbd8aa251
            pagePropertyObj.selectedPlanId: 2262
            pagePropertyObj.renewal: false
            pagePropertyObj.renewalCalendarStartDate: 
            pagePropertyObj.renewalCalendarEndDate: 
            source: 
            fuwu: 
            sso: true
            processId: buy-process-100be8b6-643f-40c3-bea7-4af8ddb3f7d3
            orderSource: product-center
            platform: pc
            statisticProductType: 01
            statisticProductId: 1538
            verifycode: 
            pagePropertyObj.pageProduct.ecInsurancplans[0].ecClauses[0].clauseId: 1539
            pagePropertyObj.pageProduct.ecInsurancplans[0].ecClauses[0].ecLiabilities[0].liabilityId: 1700
            pagePropertyObj.pageProduct.ecInsurancplans[0].ecClauses[0].ecLiabilities[0].three: 
            pagePropertyObj.pageProduct.ecInsurancplans[0].ecClauses[0].ecLiabilities[0].isSelected: true
            pagePropertyObj.pageProduct.ecInsurancplans[0].ecClauses[0].ecLiabilities[0].amount: 10
            pagePropertyObj.pageProduct.ecInsurancplans[0].ecClauses[0].ecLiabilities[1].liabilityId: 1820
            pagePropertyObj.pageProduct.ecInsurancplans[0].ecClauses[0].ecLiabilities[1].three: 
            pagePropertyObj.pageProduct.ecInsurancplans[0].ecClauses[0].ecLiabilities[1].isSelected: true
            pagePropertyObj.pageProduct.ecInsurancplans[0].ecClauses[0].ecLiabilities[1].amount: 10
            pagePropertyObj.pageProduct.ecInsurancplans[0].ecClauses[1].clauseId: 1542
            pagePropertyObj.pageProduct.ecInsurancplans[0].ecClauses[1].ecLiabilities[0].liabilityId: 1701
            pagePropertyObj.pageProduct.ecInsurancplans[0].ecClauses[1].ecLiabilities[0].three: 
            pagePropertyObj.pageProduct.ecInsurancplans[0].ecClauses[1].ecLiabilities[0].isSelected: true
            pagePropertyObj.pageProduct.ecInsurancplans[0].ecClauses[1].ecLiabilities[0].amount: 1
            pagePropertyObj.pageProduct.ecInsurancplans[0].ecClauses[2].clauseId: 1543
            pagePropertyObj.pageProduct.ecInsurancplans[0].ecClauses[2].ecLiabilities[0].liabilityId: 1702
            pagePropertyObj.pageProduct.ecInsurancplans[0].ecClauses[2].ecLiabilities[0].three: 1
            pagePropertyObj.pageProduct.ecInsurancplans[0].ecClauses[2].ecLiabilities[0].amount: 0
            pagePropertyObj.workType: 1|1201003|学生
            pagePropertyObj.occupationLevel: 1
            pagePropertyObj.occupationCode: 
            pagePropertyObj.occupationName: 
            pagePropertyObj.insuStartDate: 2020-05-02
            pagePropertyObj.insuPeriod: 1
            pagePropertyObj.insuPeriodUnit: 03
            pagePropertyObj.insuEndDate: 2021-05-01
            '''
            data = Helper.perfectJson(params)
            data["pagePropertyObj.pageProduct.ecInsurancplans[0].ecClauses[0].ecLiabilities[0].amount"] = str(
                int(int(v["accident_death"]) / 10000))
            data["pagePropertyObj.pageProduct.ecInsurancplans[0].ecClauses[0].ecLiabilities[1].amount"] = str(
                int(int(v["accident_disable"]) / 10000))
            data["pagePropertyObj.pageProduct.ecInsurancplans[0].ecClauses[1].ecLiabilities[0].amount"] = str(
                (int(v["accident_medical"]) / 10000)) if v["accident_medical"] != "0" else "0"
            data["pagePropertyObj.pageProduct.ecInsurancplans[0].ecClauses[2].ecLiabilities[0].amount"] = v[
                "accident_hospital"].replace("/天", "")
            data["pagePropertyObj.workType"] = v["professions"]
            data["pagePropertyObj.occupationLevel"] = v["professions"].split("|")[0]
            data["pagePropertyObj.occupationCode"] = v["professions"].split("|")[1] if v[
                                                                                           "professions"] != "1|1201003|学生" else ""
            data["pagePropertyObj.occupationName"] = v["professions"].split("|")[2] if v[
                                                                                           "professions"] != "1|1201003|学生" else ""
            payload = urlencode(data).replace("+", "")
            r = requests.post(url=domain[self.name]["url"], headers=domain[self.name]["header"], data=payload)

            if r.status_code == 200:
                price = Helper.decimalParse(r.json()["pagePropertyObj"]["totalPremium"])
                data = {
                    "name":self.name,
                    "company":"阳光保险集团",
                    "price":price
                }
                v["professions"] = v["professions"].split("|")[2]
                data.update( v )
                Helper.mergeTable( self.name,self.mysql,data )
    # 获取职业信息
    def getProfessionInfo(self):
        professions = []
        jbs = lambda x: pq(x)
        x = "https://product.sinosig.com/quote_quote.action?id=1538&insuredBuyNum=1&agentId=&source=&fuwu=&processId=buy-process-100be8b6-643f-40c3-bea7-4af8ddb3f7d3&orderSource=product-center&platform=pc&statisticProductType=01&statisticProductId=1538"
        items = jbs(x)(".behaviorSelect option").items()
        for item in items:
            data = {
                "name": item.text(),
                "level": item.attr("value").split("|")[0],
                "code": item.attr("value").split("|")[1],
            }
            professions.append(data)
        return professions
